package com.base.service.web.controller;

import com.base.core.lang.StringUtils;
import com.base.core.utils.R;
import com.base.sms.model.dto.NoticeDTO;
import com.base.sms.model.dto.VerifyDTO;
import com.base.sms.model.vo.VerifyVO;
import com.base.sms.exception.VerificationCodeIsNullException;
import com.base.sms.service.notice.NoticeService;
import com.base.sms.service.verification.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 短信Controller
 *
 */
@RequestMapping("/base")
@RestController
public class SmsController {

    /**
     * 手机验证码服务
     */
    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 短信通知服务
     */
    @Autowired
    private NoticeService noticeService;

    /**
     * 获取验证码
     *
     * @param phone 手机号码
     */
    @GetMapping("/sms/send/code")
    public R sendVerificationCode(@RequestParam("phone") String phone) {
        try{
            verificationCodeService.send(phone);
        }catch (Exception e){
           R.fail(e.getMessage());
        }
        return R.success();
    }

    /**
     * 获取验证码
     *
     * @param phone 手机号码
     * @param identificationCode 识别码
     * @return 验证码信息
     */
    @GetMapping("/sms/get/code")
    public R findVerificationCode(@RequestParam("phone") String phone,
                                  @RequestParam(value = "identificationCode",
                                        required = false, defaultValue = "") String identificationCode) {
        String code = verificationCodeService.find(phone, identificationCode);

        if (StringUtils.isBlank(code)) {
            throw new VerificationCodeIsNullException();
        }

        VerifyVO info = new VerifyVO();
        info.setCode(code);
        info.setIdentificationCode(identificationCode);
        info.setPhone(phone);

        return R.success(info);
    }

    /**
     * 验证信息
     *
     * @param verifyDto 验证信息
     */
    @PostMapping("/sms/verify")
    public R verifyVerificationCode(@RequestBody VerifyDTO verifyDto) {
        if (!verificationCodeService.verify(verifyDto.getPhone(), verifyDto.getCode(),
                verifyDto.getIdentificationCode())) {
            return R.fail("验证码不正确");
        }
        return R.success();
    }

    /**
     * 发送通知
     *
     * @param info 通知内容
     */
    @PostMapping("/sms/notice")
    public R sendNotice(@RequestBody NoticeDTO info) {
        boolean result = noticeService.send(info.getNoticeParams(), info.getPhones());
        if(result){
           return R.success();
        }
        return R.fail("通知发送失败");
    }
}
